<template>
	<div>
		<van-address-edit
			:area-list="areaList"
			show-postal
			show-delete
			show-set-default
			:area-columns-placeholder="['请选择', '请选择', '请选择']"
			@save="onSave"
			@delete="onDelete"
			:address-info="addressInfo"
		/>
	</div>
</template>

<script>
import { areaList } from '@vant/area-data';

import { getAddressDetailByIdAPI, saveAddressAPI, deleteAddressByIdAPI } from '@/api/address.js';

export default {
	data() {
		return {
			areaList, //标准的地区列表
			addressInfo: {
				//收货人信息初始值
				id: '', //每条地址的唯一标识
				name: '', //姓名
				tel: '', //电话
				province: '', //省份
				city: '', //城市
				county: '', //区县
				areaCode: '', //地区编码，通过省市区选择获取（必填）
				postalCode: '', //邮政编码
				addressDetail: '', //详细地址
				isDefault: false //是否选择默认
			}
		};
	},

	props: ['id'],

	created() {
		this.getAddressDetail();
	},
	methods: {
		getAddressDetail() {
			if (this.id) {
				getAddressDetailByIdAPI(this.id).then(result => {
					this.addressInfo.id = result.data.id;
					this.addressInfo.name = result.data.name;
					this.addressInfo.tel = result.data.tel;
					this.addressInfo.province = result.data.province;
					this.addressInfo.city = result.data.city;
					this.addressInfo.county = result.data.county;
					this.addressInfo.areaCode = result.data.area_code; //
					this.addressInfo.postalCode = result.data.postal_code; //
					this.addressInfo.addressDetail = result.data.address_detail; //
					this.addressInfo.isDefault = result.data.is_default == 1 ? true : false; //
				});
			}
		},

		//处理保存地址
		onSave(content) {
			//准备参数
			let params = {
				id: content.id,
				name: content.name,
				tel: content.tel,
				province: content.province,
				city: content.city,
				county: content.county,
				area_code: content.areaCode, //
				postal_code: content.postalCode, //
				address_detail: content.addressDetail, //
				is_default: content.isDefault == true ? 1 : 0 //
			};

			saveAddressAPI(params).then(result => {
				this.$toast(result.msg);
				//页面跳转 上一页面
				setTimeout(() => {
					this.$router.go(-1);
				}, 10);
			});
		},

		// 处理删除地址
		onDelete(content) {
			let id = content.id;
			if (!id) return;

			deleteAddressByIdAPI(id).then(result => {
				this.$toast(result.msg);
				//页面跳转 上一页面
				setTimeout(() => {
					this.$router.go(-1);
				}, 10);
			});
		}
	}
};
</script>

<style></style>
